package com.ruoyi.web.controller.kycinfo;


import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.constant.KycConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.KycUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.kycinfo.domain.*;
import com.ruoyi.kycinfo.dto.KycUserInfoDTO;
import com.ruoyi.kycinfo.service.*;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2023-10-09
 */


@RestController
@RequestMapping("/kycinfo/userinfo")
public class KycUserInfoController extends BaseController {
    @Autowired
    private ISysUserService SysUserService;

    @Autowired
    private IKycUserInfoService kycUserInfoService;

    @Autowired
    private IKycFamilyService kycFamilyService;

    @Autowired
    private IKycWorkService kycWorkService;

    @Autowired
    private IKycProductService kycProductService;

    @Autowired
    private IKycPotentialService kycPotentialService;

    @Autowired
    private IKycContactService kycContactService;


    /**
     * 查询 KycUserInfo列表
     */
   /* @PreAuthorize("@ss.hasPermi('kycinfo:userinfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(KycUserInfo kycUserInfo)
    {
        startPage();
        List<KycUserInfo> list = kycUserInfoService.selectKycUserInfoList(kycUserInfo);

        return getDataTable(list);
    }*/


    /**
     * 查询 KycUserInfo列表
     * 支行客户只能看到自己的客户的 KycUserInfo信息
     * 支行管理岗可以看到该该支行所有支行客户岗的客户
     */
    @PreAuthorize("@ss.hasPermi('kycinfo:userinfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(KycUserInfo kycUserInfo) {
        // 获取当前用户ID
        Long curUserId = SecurityUtils.getUserId();
        List<Long> userIdList = new ArrayList<>();
        userIdList.add(curUserId);
        // userIdList 中加入其他支行客户岗员工的userId
        SysUser user = new SysUser();
        List<SysUser> users = SysUserService.selectUserList(user);
        for (SysUser sysUser : users) {
            userIdList.add(sysUser.getUserId());
        }

        startPage();
        // 查询kycUserInfo信息
        List<KycUserInfo> list = kycUserInfoService.selectKycUserInfoListByUserIdList(userIdList);
        for (KycUserInfo userInfo : list) {
            SysUser sysUser = SysUserService.selectUserById(userInfo.getUserId());
            userInfo.setNickName(sysUser.getNickName());
        }

        return getDataTable(list);
    }


    /**
     * 导出【请填写功能名称】列表
     */
    @ApiOperation("导出系统用户信息")
    @PreAuthorize("@ss.hasPermi('kycinfo:userinfo:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, KycUserInfo kycUserInfo) {
        List<KycUserInfo> list = kycUserInfoService.selectKycUserInfoList(kycUserInfo);
        ExcelUtil<KycUserInfo> util = new ExcelUtil<KycUserInfo>(KycUserInfo.class);
        util.exportExcel(response, list, "客户数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('kycinfo:userinfo:query')")
    @GetMapping(value = "/{userInfoId}")
    public AjaxResult getInfo(@PathVariable("userInfoId") Long userInfoId) {
        KycUserInfo kycUserInfo = kycUserInfoService.selectKycUserInfoByUserInfoId(userInfoId);
        return success(kycUserInfoService.selectKycUserInfoByUserInfoId(userInfoId));
    }

    /*
        修改客户信息查询接口
     */
    @ApiOperation("修改客户信息查询接口")
    @PreAuthorize("@ss.hasPermi('kycinfo:userinfo:query')")
    @GetMapping(value = "update/{userInfoId}")
    public AjaxResult getUpdateInfo(@PathVariable("userInfoId") Long userInfoId) {
        KycUserInfo kycUserInfo = kycUserInfoService.selectKycUserInfoByUserInfoId(userInfoId);
        KycWork kycWork = kycWorkService.selectKycWorkByUserInfoId(userInfoId);
        KycProduct kycProduct = kycProductService.selectKycProductByUserInfoId(userInfoId);
        List families = kycFamilyService.selectKycFamilyListByUserInfoId(userInfoId);

        //System.out.println(kycUserInfo);
        //System.out.println(kycProduct);
        //System.out.println(kycWork);

        // 对”其他“相关字段进行特殊处理
        // KycUserInfo 客户类型
        String[] clienTypeStr = KycUtils.processOther(kycUserInfo.getClienType(), KycConstants.CLIENTYPE_LIST);
        kycUserInfo.setClienType(clienTypeStr[0]);
        kycUserInfo.setClienTypeOther(clienTypeStr[1]);

        // KycWork 持有签证或曾经去过
        if (kycWork != null) {//判空防止空指针
            String[] countryStr = KycUtils.processOther(kycWork.getCountry(), KycConstants.COUNTRY_LIST);
            kycWork.setCountry(countryStr[0]);
            kycWork.setCountryOther(countryStr[1]);
        } else {//在数据库中以userInfoId值创建一个kycWork行
            kycWork = new KycWork();
            kycWork.setUserInfoId(userInfoId);
            kycWorkService.insertKycWork(kycWork);
        }


        if (kycProduct != null) {      //判空防止空指针
            // kycProduct
            // 重点交叉产品
            String[] keyProductStr = KycUtils.processOther(kycProduct.getKeyProduct(), KycConstants.KEYPRODUCT_LIST);
            kycProduct.setKeyProduct(keyProductStr[0]);
            kycProduct.setKeyProductOther(keyProductStr[1]);

            // 在我行贷款原因
            String[] myLoanReasonStr = KycUtils.processOther(kycProduct.getMyLoanReason(), KycConstants.MYLOANREASON_LIST);
            kycProduct.setMyLoanReason(myLoanReasonStr[0]);
            kycProduct.setMyLoanReasonOther(myLoanReasonStr[1]);

            // 在他行贷款原因
            String[] otherLoanReasonOther = KycUtils.processOther(kycProduct.getOtherLoanReason(), KycConstants.OTHERLOANREASON_LIST);
            kycProduct.setOtherLoanReason(otherLoanReasonOther[0]);
            kycProduct.setOtherLoanReasonOther(otherLoanReasonOther[1]);

            // 借记卡
            String[] debitCardTypeStr = KycUtils.processOther(kycProduct.getDebitCardType(), KycConstants.DEBITCARDTYPE_LIST);
            kycProduct.setDebitCardType(debitCardTypeStr[0]);
            kycProduct.setDebitCardTypeOther(debitCardTypeStr[1]);

            // 存款
            String[] depositTypeStr = KycUtils.processOther(kycProduct.getDepositType(), KycConstants.DEPOSITTYPE_LIST);
            kycProduct.setDepositType(depositTypeStr[0]);
            kycProduct.setDepositTypeOther(depositTypeStr[1]);

            // 基金
            String[] fundStr = KycUtils.processOther(kycProduct.getFund(), KycConstants.FUND_LIST);
            kycProduct.setFund(fundStr[0]);
            kycProduct.setFundOther(fundStr[1]);

            // 保险
            String[] insuranceStr = KycUtils.processOther(kycProduct.getInsurance(), KycConstants.INSURANCE_LIST);
            kycProduct.setInsurance(insuranceStr[0]);
            kycProduct.setInsuranceOther(insuranceStr[1]);

            // 偏爱活动主题
            String[] activityStr = KycUtils.processOther(kycProduct.getActivity(), KycConstants.ACTIVITY_LIST);
            kycProduct.setActivity(activityStr[0]);
            kycProduct.setActivityOther(activityStr[1]);
        } else {//在数据库中以userInfoId值创建一个kycProduct行
            kycProduct = new KycProduct();
            kycProduct.setUserInfoId(userInfoId);
            kycProductService.insertKycProduct(kycProduct);
        }

        // 开始封装查询结果
        KycUserInfoDTO kycUserInfoDTO = new KycUserInfoDTO();
        kycUserInfoDTO.setKycUserInfo(kycUserInfo);
        kycUserInfoDTO.setKycWork(kycWork);
        kycUserInfoDTO.setKycProduct(kycProduct);
        kycUserInfoDTO.setKycFamilyList(families);
//        System.out.println(kycUserInfoDTO);
        return success(kycUserInfoDTO);
    }

    /**
     * 修改客户信息接口
     */
    @ApiOperation("修改客户信息接口")
    @PreAuthorize("@ss.hasPermi('kycinfo:userinfo:edit')")
    @Log(title = "修改客户信息接口", businessType = BusinessType.UPDATE)
    @PutMapping("update")
    public AjaxResult editUpdate(@RequestBody KycUserInfoDTO kycUserInfoDTO) {
        KycUserInfo kycUserInfo = kycUserInfoDTO.getKycUserInfo();
        if (kycUserInfo != null) {
            // kcyUserinfo表 客户类型字段
            String clienTypeOther = kycUserInfo.getClienTypeOther();
            if (!StringUtils.isEmpty(clienTypeOther)) {
                String clienType = kycUserInfo.getClienType();
                clienType = clienType + "," + clienTypeOther;
                kycUserInfo.setClienType(clienType);
            }
            // 这里更新的kycUserInfo必须要有userInfoId字段 todo
            kycUserInfoService.updateKycUserInfo(kycUserInfo);
        }

        KycWork kycWork = kycUserInfoDTO.getKycWork();
        if (kycWork != null) {
            // 持有签证或曾经去过
            // "其他"字段 有可能获取到  null
            String countryOther = kycWork.getCountryOther();
            if (!StringUtils.isEmpty(countryOther)) {
                String country = kycWork.getCountry();
                country = country + "," + countryOther;
                kycWork.setCountry(country);
            }

            kycWorkService.updateKycWork(kycWork);
        }

        KycProduct kycProduct = kycUserInfoDTO.getKycProduct();
        if (kycProduct != null) {
            // 重点交叉产品
            // "其他"字段 有可能获取到  null
            String keyProductOther = kycProduct.getKeyProductOther();
            if (!StringUtils.isEmpty(keyProductOther)) {
                String keyProduct = kycProduct.getKeyProduct();
                keyProduct = keyProduct + "," + keyProductOther;
                kycProduct.setKeyProduct(keyProduct);
            }

            // 在我行贷款原因
            // "其他"字段 有可能获取到  null
            String myLoanReasonOther = kycProduct.getMyLoanReasonOther();
            if (!StringUtils.isEmpty(myLoanReasonOther)) {
                String myLoanReason = kycProduct.getMyLoanReason();
                myLoanReason = myLoanReason + "," + myLoanReasonOther;
                kycProduct.setMyLoanReason(myLoanReason);
            }

            // 在他行贷款原因
            // "其他"字段 有可能获取到  null
            String otherLoanReasonOther = kycProduct.getOtherLoanReasonOther();
            if (!StringUtils.isEmpty(otherLoanReasonOther)) {
                String otherLoanReason = kycProduct.getOtherLoanReason();
                otherLoanReason = otherLoanReason + "," + otherLoanReasonOther;
                kycProduct.setOtherLoanReason(otherLoanReason);
            }

            // 借记卡
            // "其他"字段 有可能获取到  null
            String debitCardTypeOther = kycProduct.getDebitCardTypeOther();
            if (!StringUtils.isEmpty(debitCardTypeOther)) {
                String debitCardType = kycProduct.getDebitCardType();
                debitCardType = debitCardType + "," + debitCardTypeOther;
                kycProduct.setDebitCardType(debitCardType);
            }

            // 存款
            // "其他"字段 有可能获取到  null
            String depositTypeOther = kycProduct.getDepositTypeOther();
            if (!StringUtils.isEmpty(depositTypeOther)) {
                String depositType = kycProduct.getDepositType();
                depositType = depositType + "," + depositTypeOther;
                kycProduct.setDepositType(depositType);
            }

            // 基金
            // "其他"字段 有可能获取到  null
            String fundOther = kycProduct.getFundOther();
            if (!StringUtils.isEmpty(fundOther)) {
                String fund = kycProduct.getFund();
                fund = fund + "," + fundOther;
                kycProduct.setFund(fund);
            }

            // 保险
            // "其他"字段 有可能获取到  null
            String insuranceOther = kycProduct.getInsuranceOther();
            if (!StringUtils.isEmpty(insuranceOther)) {
                String insurance = kycProduct.getInsurance();
                insurance = insurance + "," + insuranceOther;
                kycProduct.setInsurance(insurance);
            }

            // 偏爱活动主题
            // "其他"字段 有可能获取到  null
            String activityOther = kycProduct.getActivityOther();
            if (!StringUtils.isEmpty(activityOther)) {
                String activity = kycProduct.getActivity();
                activity = activity + "," + activityOther;
                kycProduct.setActivity(activity);
            }

            kycProductService.updateKycProduct(kycProduct);
        }

//        System.out.println(kycUserInfoDTO.getKycFamilyList());

        if ((kycUserInfoDTO.getKycFamilyList()) != null) {
            for (KycFamily kycFamily : kycUserInfoDTO.getKycFamilyList()) {
                // 如果是新增数据，这里kycFamily.getFamilyId()返回的是null
                if ((kycFamilyService.selectKycFamilyByFamilyId(kycFamily.getFamilyId())) != null) {
                    kycFamilyService.updateKycFamily(kycFamily);
                } else {
                    kycFamily.setUserInfoId(kycUserInfoDTO.getKycUserInfo().getUserInfoId());
                    kycFamilyService.insertKycFamily(kycFamily);
                }
            }
        }
        return toAjax(kycUserInfoService.updateKycUserInfo(kycUserInfoDTO.getKycUserInfo()));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('kycinfo:userinfo:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody KycUserInfo kycUserInfo) {
        return toAjax(kycUserInfoService.insertKycUserInfo(kycUserInfo));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('kycinfo:userinfo:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody KycUserInfo kycUserInfo) {
        return toAjax(kycUserInfoService.updateKycUserInfo(kycUserInfo));
    }

    /**
     * 删除客户信息：个人信息，家庭信息，工作信息，金融产品覆盖信息，潜力洞察信息，联络情况信息
     */
    @PreAuthorize("@ss.hasPermi('kycinfo:userinfo:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @Transactional
    @DeleteMapping("/{userInfoIds}")
    public AjaxResult remove(@PathVariable Long[] userInfoIds) {
        if (userInfoIds == null || userInfoIds.length == 0) {
            return toAjax(0);
        }

        // 删除家庭信息
        kycFamilyService.deleteKycFamilyByUserInfoIds(userInfoIds);

        // 删除工作信息
        kycWorkService.deleteKycWorkByUserInfoIds(userInfoIds);

        // 删除金融产品覆盖信息
        kycProductService.deleteKycProductByUserInfoIds(userInfoIds);

        // 删除潜力洞察信息
        kycPotentialService.deleteKycPotentialByUserInfoIds(userInfoIds);

        // 删除联络情况信息
        kycContactService.deleteKycContactByUserInfoIds(userInfoIds);

        // 删除客户个人信息
        return toAjax(kycUserInfoService.deleteKycUserInfoByUserInfoIds(userInfoIds));
    }
}
